GameplayInputSystem框架

输入系统需要把物理按键转换成语义动作,同时支持短按、长按、禁用原因和 UI 操作。设备映射与语义事件分别变化,消费者只处理动作身份与输入阶段。

这里以 Enhanced Input 为底层,InputAction 保存行为模板,PlayerController 上的 Component 管理运行实例与阶段回调;Widget 按键和拖拽分别作为可组合能力接入。

基础架构

图中按职责分组列出核心类;+、-、# 表示公开、私有和受保护成员。字段类型保留容器与指针语义,TMap 的键和值用 | 分隔,分组不代表额外的源码命名空间。

%%{init: {"class": {"useMaxWidth": false}, "flowchart": {"useMaxWidth": false}}}%%
classDiagram
    direction LR

    namespace Definition {
        class UGameplayInputAction
    }

    namespace Runtime {
        class UGameplayInputComponent
    }

    namespace Extension {
        class UGameplayInputEventBase
    }

    UGameplayInputComponent --> UGameplayInputAction : 配置引用
    UGameplayInputAction --> UGameplayInputEventBase : InputEvent 模板
    UGameplayInputComponent *-- UGameplayInputEventBase : RuntimeInputEvents
    UGameplayInputEventBase --> UGameplayInputComponent : Owner 弱引用

    class UGameplayInputAction {
        - InputNameOverride : FString
        - InputEvent : TObjectPtr~UGameplayInputEventBase~
        + GetInputName() FString
        + GetInputEventTemplate()
    }

    class UGameplayInputComponent {
        - InputMappingContexts : TArray~TObjectPtr~UInputMappingContext~~
        - RuntimeInputConfigs : TMap~const UInputAction*|FGameplayInputRuntimeConfig~
        - ActiveInputStates : TMap~const UInputAction*|FGameplayInputActiveState~
        - RuntimeInputEvents : TArray~TObjectPtr~UGameplayInputEventBase~~
        - DisabledInputReasons : TSet~FName~
        + SetInputEnabled(bEnabled, Reason)
        - BuildRuntimeInputConfigs()
        - HandleInputActionFinished(InputActionInstance)
    }

    class UGameplayInputEventBase {
        - Owner : TWeakObjectPtr~UGameplayInputComponent~
        - InputAction : TWeakObjectPtr~const UInputAction~
        # CanStartInput() bool
        # OnPressed()
        # OnTriggered()
        # OnReleased()
    }

IMC 负责物理映射,InputName 标识语义 Action,Notify Key 标识通知类型。三种身份分别属于设备、动作与消息层,修改映射不会改变下游事件契约。

配置、解析结果与活动状态

输入资产的名字与执行状态分开保存。FGameplayInputConfig 是显式配置项,组件将资产和触发器信息整理成 FGameplayInputRuntimeConfig,再用 FGameplayInputActiveState 记录一次活动输入是否已经触发。下面节选字段,省略构造器和反射声明。

1
2
3
4
5
struct FGameplayInputConfig
{
FString InputName = {};
TObjectPtr<const UInputAction> InputAction = nullptr;
};
1
2
3
4
5
6
7
8
struct FGameplayInputRuntimeConfig
{
FString InputName;
const UInputAction* InputAction = nullptr;
float TriggerTimeThreshold = 0.0f;
EGameplayInputTriggerMode TriggerMode = EGameplayInputTriggerMode::Immediate;
bool bLegacy = false;
};
1
2
3
4
struct FGameplayInputActiveState
{
bool bTriggered = false;
};

InputAction 是配置与运行查询的连接点,InputName 提供语义身份;运行表按资产对象索引,不能仅凭同名字符串认定是同一条物理输入。TriggerMode 默认立即触发,TriggerTimeThreshold 保存解析后的时间阈值,bLegacy 区分旧入口的兼容路径。

bTriggered 属于本次活动输入,结束时从 ActiveInputStates 移除。RuntimeInputEvents 则保存当前组件复制出来的事件对象,可跨单次按下与释放复用;它们的销毁时机是组件输入配置卸载。配置、事件实例与一次按键状态因此具有三个不同的生命周期。

初始化与运行实例

Component 在本地 PlayerController 上初始化:

  1. 向 LocalPlayer Enhanced Input Subsystem 注册 IMC 和优先级;
  2. 扫描映射中的 GameplayInputAction;
  3. 建立 Action、InputName、触发模式与阈值索引;
  4. 绑定 Started、Ongoing、Triggered、Completed、Canceled;
  5. Duplicate 内嵌 InputEvent,Outer 为当前 Component,再执行 Initialize。

Action 资产中的 Event 是共享模板,不能保存当前持有者的按住时长或目标。运行时副本使多个持有者使用同一资产时不会共享输入状态。

EndPlay 反向卸载 Event,再移除绑定、IMC、索引与禁用原因。输入链仅在本地执行,不复制 Event 对象。

输入阶段

Enhanced Input 阶段 组件行为
Started 检查开关与 CanStartInput,记录活动输入,发 Pressed
Ongoing 等待触发条件,更新 Hold 进度并复验可用性
Triggered 再次检查条件,同次活动输入只执行业务一次
Completed / Canceled 摘除活动状态,关闭进度,发 Released 清理

Event 的 Released 业务回调与清理通知不同:只有已经触发且仍允许输入时才执行释放业务;被系统禁用取消的输入仍应通知 UI 关闭高亮,释放清理不再触发领域提交。

活动输入的状态机

组件把 Enhanced Input 的阶段流收敛为一次活动输入。运行事件副本解释语义,ActiveInputStates 保存本次输入是否已经触发。

Started 先登记活动状态,后派发按下通知:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void UGameplayInputComponent::HandleInputActionStarted(
const FInputActionInstance& InputActionInstance)
{
if (!UKismetSystemLibrary::IsStandaloneOrClient(this))
return;

const UInputAction* InputAction = InputActionInstance.GetSourceAction();
const FGameplayInputRuntimeConfig* Config = FindRuntimeInputConfig(InputAction);
if (Config == nullptr || ActiveInputStates.Contains(InputAction) ||
!CanStartInputAction(InputAction))
return;

ActiveInputStates.Add(InputAction);
DispatchPressed(*Config);
if (!IsInputEnabled() || !ActiveInputStates.Contains(InputAction))
return;
if (Config->TriggerMode == EGameplayInputTriggerMode::Hold)
{
DispatchHoldProgress(*Config, 0.0f, true);
}
}

DispatchPressed 可以同步禁用输入或取消当前动作,所以返回后要复验启用状态和记录是否仍存在,再开启 Hold 进度。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
void UGameplayInputComponent::HandleInputActionTriggered(
const FInputActionInstance& InputActionInstance)
{
if (!UKismetSystemLibrary::IsStandaloneOrClient(this))
return;

const UInputAction* InputAction = InputActionInstance.GetSourceAction();
const FGameplayInputRuntimeConfig* Config = FindRuntimeInputConfig(InputAction);
FGameplayInputActiveState* State = ActiveInputStates.Find(InputAction);
if (Config == nullptr || State == nullptr || State->bTriggered)
return;
if (!CanStartInputAction(InputAction))
{
CancelBlockedInputAction(*Config, InputAction, InputActionInstance.GetElapsedTime());
return;
}

State->bTriggered = true;
float HeldDuration = InputActionInstance.GetElapsedTime();
if (Config->TriggerMode == EGameplayInputTriggerMode::Hold)
{
HeldDuration = FMath::Max(HeldDuration, Config->TriggerTimeThreshold);
DispatchHoldProgress(*Config, HeldDuration, true);
DispatchLongPressed(*Config, HeldDuration);
}
else if (Config->TriggerMode == EGameplayInputTriggerMode::Tap)
{
DispatchShortPressed(*Config, HeldDuration);
}

DispatchTriggered(*Config);
}

void UGameplayInputComponent::CancelBlockedInputAction(const FGameplayInputRuntimeConfig& Config,
const UInputAction* InputAction,
float HeldDuration)
{
ActiveInputStates.Remove(InputAction);
if (Config.TriggerMode == EGameplayInputTriggerMode::Hold)
{
DispatchHoldProgress(Config, 0.0f, false);
}
DispatchReleased(Config, HeldDuration, false);
}

bTriggered 在派发前置位,因此同一活动期内重复到达 Triggered 会被入口拒绝。Hold 的时长下限取触发门槛,Tap 则使用实际经过时间;两者最终汇合到统一触发派发。执行资格中途消失时,CancelBlockedInputAction 移除活动记录并结束显示进度,但不给动作层补发一次成功释放。

触发标记先写入再调用节点,活动记录先摘除再释放,防止回调重入导致重复提交。业务 Released 与释放清理分开,保证取消也能结束表现状态,而不会再执行一次动作。

Tap 与 Hold

同一个物理键可以映射两个 Action,分别配置 Tap 与 Hold,并使用共同阈值 T:Tap 在小于 T 时释放,Hold 在达到 T 时触发。

sequenceDiagram
    participant K as 物理键
    participant T as Tap Action
    participant H as Hold Action
    participant B as 业务
    K->>T: Started
    K->>H: Started
    alt 小于阈值释放
        T->>B: Triggered
        H->>H: Canceled
    else 达到阈值
        H->>B: Triggered 一次
        T->>T: 不选中
    end

两个候选都可能产生 Pressed,因此不能在 Pressed 就执行短按业务。真正选择结果来自 Triggered,组件再保证长按持续期间不反复提交同一业务。

Hold 进度用于表现,从 0 到 1,释放或取消时通过 bIsActive=false 关闭。计时由 Enhanced Input Trigger 提供,不再增加另一套可能漂移的长按计时器。

语义通知

外部消费者订阅模块级 Delegate,包括 Pressed、Triggered、Released、ShortPressed、LongPressed、HoldProgress 与 Notify。

Notify Event 在 Triggered 中发送 Key 与 Params,消费方把语义意图转换为领域请求。输入节点不持有领域提交逻辑,使设备映射与玩法执行可以独立变化。

委托带来源 PlayerController。分屏或单进程多 World 中必须过滤自己的 Controller,退出时成对解绑;不能假定进程中只有一个持有者。

原因集合与取消传播

输入可用性由具名原因集合决定。每个来源只管理自己的原因,集合表达组合状态,不使用一个由多个模块反复覆盖的布尔值。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
void UGameplayInputComponent::SetInputEnabled(bool bEnabled, FName Reason)
{
if (!UKismetSystemLibrary::IsStandaloneOrClient(this))
return;
if (Reason.IsNone())
{
return;
}

const bool bWasEnabled = IsInputEnabled();
if (bEnabled)
{
if (DisabledInputReasons.Remove(Reason) == 0)
return;
}
else
{
if (DisabledInputReasons.Contains(Reason))
return;
DisabledInputReasons.Add(Reason);
}

if (!bWasEnabled || IsInputEnabled())
return;

TArray<const UInputAction*> ActiveActions;
ActiveInputStates.GetKeys(ActiveActions);
for (const UInputAction* InputAction : ActiveActions)
{
if (const FGameplayInputRuntimeConfig* Config = FindRuntimeInputConfig(InputAction))
{
const FGameplayInputRuntimeConfig ConfigCopy = *Config;
CancelBlockedInputAction(ConfigCopy, InputAction, 0.0f);
}
}
}

恢复请求只移除自己的 Reason,不能清空其它模块的禁用请求。只有从启用切换到禁用时才遍历活动输入;遍历前复制 Key 列表,取消前再复制 RuntimeConfig,使释放回调修改绑定集合时不会继续使用原容器中的配置引用。取消派发仍须遵守组件生命周期契约,这份快照不代表任意注册表重建都已具备事务语义。

相同原因重复添加不叠加计数;最后一个原因移除后,组件等待下一次新的输入,不补发已经取消的事件。这个开关属于本地输入解释层,服务端资格与其它输入通道分别拥有自己的规则。

Widget KeyHandler

KeyHandler 作为 UserWidget Extension 持有 Slate IInputProcessor。处理前检查 Widget 可见性、LocalPlayer、Slate User 和焦点范围,再调用 OnKeyDown;返回 true 消费本次按键。

它不主动抢焦点,也不预设 Escape 或 Tab 的业务含义。创建时保存 Handler,关闭时注销预处理器并移除 Extension,避免界面每次打开都重复登记。

派发前复制 Delegate,允许回调同步关闭自身 Widget。多个 Handler 的层级优先级需要由界面管理器明确仲裁,不能仅依赖注册顺序。

UI 拖拽

拖拽继续使用 UE 的阈值检测、命中和松开路由。Operation 保存:

字段 作用
DragType 标识载荷的协议类型
Scope 限制可接受范围
Payload 强持有本次载荷
DefaultDragVisual 强持有预览
Source 来源弱引用
Accepted / Finished 一次接受与结束状态

GetDragPayload 验证类型、Scope、World、LocalPlayer 与来源有效性。AcceptDrag 在同样校验后消费接受权,一次 Operation 最多接受一次。

拖拽操作对象保存 Scope、Payload 和 Visual。目标在 DragEnter 阶段只计算接受资格与高亮;OnDrop 返回是否接受载荷,权威请求仍由操作层发送。操作完成或取消时统一清理预览、高亮和临时引用,使 UI 悬停状态与领域提交结果分开。

Accept 表示 UI 交互已接受,不表示领域状态已经提交。异步结果由对应系统返回,Operation 结束通知只负责清理,不再次提交同一请求。

列表项回收时清理绑定与高亮,界面隐藏时取消自己 Scope 的活动拖拽。Operation 对载荷强持有,对 Source 与 Scope 弱持有,可以让载荷活到操作结束,同时不阻止来源界面退出。

扩展点与依赖方向

InputEvent 扩展游戏动作语义,Notify Event 提供纯消息,KeyHandler 处理 Widget 范围内的按键,Drag Operation 处理载荷与接受权。这些扩展共享本地用户上下文,但各自保持独立生命周期。

输入层只输出意图与交互结果。下游系统拥有授权、资源和最终状态,UI 接受拖拽也不等于领域操作已经提交。退出时先取消活动过程,再解除 Event、绑定与 IMC,避免已失去来源的回调继续派发。

结束输入时先移除活动状态

ActiveInputStates 记录一次输入是否仍处于活动期,以及是否已经触发。结束事件先读出所需标记,再移除活动记录,最后派发通知。核心分支如下,省略入口的执行端检查:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const auto* Config = FindRuntimeInputConfig(InputAction);
const auto* State = ActiveInputStates.Find(InputAction);
if (Config == nullptr || State == nullptr)
return;

const bool bExecuteGameplayCallback = State->bTriggered;
ActiveInputStates.Remove(InputAction);

const float HeldDuration = InputActionInstance.GetElapsedTime();
if (Config->TriggerMode == EGameplayInputTriggerMode::Hold)
{
DispatchHoldProgress(*Config, HeldDuration, false);
}
DispatchReleased(*Config, HeldDuration, bExecuteGameplayCallback);

Remove 必须发生在回调之前。回调可能关闭输入、注销绑定,或者间接再次走到结束入口;此时旧活动记录已经不存在,重复结束会在查找阶段返回。移除后也不再读取原 State 指针,因为容器修改可能使它失效。

Released 通知与实际动作回调分开控制:输入生命周期需要完成收尾,但动作回调还要满足本次曾触发、当前输入仍启用等条件。派发时复制回调结构,避免调用某个委托期间修改注册表,导致同一轮继续访问被移除的委托存储。

HeldDuration 取自输入实例的同一时间来源,短按与长按据此解释同一段持有过程。框架不额外累计另一份 DeltaTime,从而减少暂停、采样频率变化时的判定分歧。